const nodemailer = require('nodemailer');
const config = require("../config/mail.json");

class Sendmail {
  /**
   * 构造函数
   */
  constructor() {
    this.mailChoise = "qyqq";
    // 发送人邮件配置
    this.params = config[this.mailChoise];
    this.transporter = nodemailer.createTransport(this.params);

    // 接收人邮件地址初始化
    this.options = {
      from: config[this.mailChoise].auth.user,   // 发件人 - 必须与auth用户一致
      to: "554900329@qq.com",  // 收件人
      subject: "测试邮件发送",  // 标题
      // text: "hello world!",   // 纯文本
      html: "<h1>Hello World</h1>"  // html格式
    };
  }
  /**
   * 发送邮件
   * @param {object} options 接收人邮件配置
   */
  send(options) {
    if (options) {
      let type = Object.prototype.toString.call(options);
      if (type == '[object Object]') {
        options.from && delete options.from;
        this.options = Object.assign({}, this.options, options);
      } else {
        throw new Error("options must be object!");
      }
    }
    return new Promise((resolve, reject) => {
      this.transporter.sendMail(this.options, function (err, info) {
        if (err) reject(err);
        resolve(info);
      })
    })
  }
}


module.exports = Sendmail;